import logging
import os
from logging.handlers import RotatingFileHandler
from datetime import datetime

def setup_logging():
    """配置项目日志系统"""
    
    # 获取当前文件的父目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    parent_dir = os.path.dirname(current_dir)

    # 创建日志目录路径
    log_dir = os.path.join(parent_dir, "logs")

    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 基础配置
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # 创建主logger
    logger = logging.getLogger('production_system')
    logger.setLevel(logging.INFO)
    
    # 文件处理器（按日期滚动）
    log_file = os.path.join(log_dir, f"production_system_{datetime.now().strftime('%Y%m%d')}.log")
    file_handler = RotatingFileHandler(
        log_file, 
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
    ))
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(logging.Formatter(
        '%(asctime)s - %(levelname)s - %(message)s'
    ))
    
    # 添加处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger

# 创建全局logger实例
logger = setup_logging()